#! /usr/bin/perl

# example of usage: ./battle.pl a1 a10 j1 j10 c1c2 h1h2 e1f1 f10h10 d8d10 f5f8

use 5.010; # MINIMAL version of perl
use strict; # strict grammar
use warnings; # warning about transrormation from string to number

my $argc=@ARGV;
if ($argc==0)
{say "Example of usage: ./battle.pl a1 a10 j1 j10 c1c2 h1h2 e1f1 f10h10 d8d10 f5f8";}
if ($argc!=10)
{
say "Invalid number of arguements.";
say "Example of usage: ./battle.pl a1 a10 j1 j10 c1c2 h1h2 e1f1 f10h10 d8d10 f5f8";
exit -1;
}
# init hash of letters & digits
my @letter;
foreach  (1..10)
{
push(@letter, chr($_+96)); # from int to char
push(@letter, $_);
}

my %h=@letter;		# hash of letters & digits

my @small;	# horizontal array
foreach (1..10)
{$small[$_]='~';}


my @field;  ## 2-dim array
foreach (1..10)
{push (@field,[@small]);}

#	processing of parameters
my $col1;
my $row1;
my $col2;
my $row2;
foreach my $i (0..9)
{
if ( ((length ($ARGV[$i]) == 2) || (length ($ARGV[$i]) == 3))  &&
$ARGV[$i] =~ m/(^[a-j][1-9]|[10]$)/)
{ # put '+' for a simple ship substr
if (exists $h{substr $ARGV[$i],0,1})
{$field[substr ($ARGV[$i],1)-1][$h{substr $ARGV[$i],0,1} ]='+';}
else
{
say "From \'a\' to \'j\'!";
exit -1;
}
}

elsif ($ARGV[$i] =~ m/([1-9])/g) # m/([1-9]|[10])/g) 
{
if (exists $h{substr $`,0,1})
{ $col1=$h{ substr $`,0,1 };} #) {}  else {die "Hard!   "};
else
{
say "From \'a\' to \'j\'!";
exit -1;
}
if ( length $ARGV[$i]==6 ) # "10" is used twice
{
$row1=(substr $ARGV[$i],1,2)-1;
if (exists $h{substr $',1,1})
{ $col2=$h{ substr $',1,1 };}
else
{
say "From \'a\' to \'j\'!";
exit -1;
}
$row2=substr($',2)-1;
}
else
{
 $row1=$&-1;
if (exists $h{substr $',0,1})
 { $col2=$h{ substr $',0,1 };}
else
{
say "From \'a\' to \'j\'!";
exit -1;
}
 $row2=substr($',1)-1;
}

	if ($row2-$row1>3 || $col2-$col1>3)
	{die "Wrong size!";}
	elsif ($row2==$row1 && $col2!=$col1)	# horizontal ship
	{
	foreach my $c ($col1..$col2)
	{
	if ($field[$row2][$c]=~/\~/)
	{$field[$row2][$c]='+';}
	else 
	{die "Wrong coordinates! $row2   $c  $ARGV[$i] $field[$row2][$c]";}
	}
	}
	elsif ($row2!=$row1 && $col2==$col1)	# vertical ship
	{
	foreach my $r ($row1..$row2)
	{
	if ($field[$r][$col2]=~/\~/)
	{$field[$r][$col2]='+';}
	else
	{die "Wrong coordinates! $r $col2  $ARGV[$i] is $field[$r][$col2]";}
	}	
	}
	elsif ($row2==$row1 && $col2==$col1)
	{$field[$row2][$col2]='+';}
	else 
	{
	say "Wrong parameters!";
	exit -1;
	}
}
else 
{
say "Wrong parameters!";
exit -1;}
}

# 	print the field
print "\ta b c d e f g h i j\n"; # 	print letters
foreach my $i (0..9)	
{
print $i+1,"\t";	# print numbers
foreach my $l (1..10)
{ print $field[$i][$l], ' ' ;}
print "\n";
}
